package cn.bjit.mq;

import cn.bjit.model.OrderMessage;
import cn.bjit.service.ProductOrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Slf4j
@Component
@RabbitListener(queues = "${mqconfig.order_close_queue}")
public class ProductOrderMQListener {

    @Resource
    private ProductOrderService productOrderService;


    /**
     * @param orderMessage
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    public void closeProductOrder(OrderMessage orderMessage, Message message, Channel channel) throws IOException {
        log.info("监听到消息：closeProductOrder:{}",orderMessage);
        //获取消息的编号
        long msgTag = message.getMessageProperties().getDeliveryTag();
        try{
            //定时关单
            boolean flag = productOrderService.closeProductOrder(orderMessage);
            if(flag){
                channel.basicAck(msgTag,false);   // 确认消息
            }else {
                channel.basicReject(msgTag,true); //重新入队列
            }
        }catch (IOException e){
            log.error("定时关单失败:",orderMessage);   //人工排查
            channel.basicReject(msgTag,true);
        }
    }
}
